package com.example.springboot.mqtt.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.springboot.mqtt.config.AipocrConfig;
import com.example.springboot.mqtt.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;

@RestController
public class MqttClientController {

    @Autowired
    private MqttUtil mqttUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AipocrConfig aipOcrConfig;

    @GetMapping("/pushMqtt")
    public String pushMqtt(@RequestParam("topic") String  topic,
                           @RequestParam("message") String message) {
        mqttUtil.publish(topic, message);
        return "success";
    }

    @GetMapping("/subMqtt")
    public String subMqtt(@RequestParam("topic") String topic) {
        mqttUtil.subscribe(topic);
        return "success";
    }

    @GetMapping("/unsubMqtt")
    public String unsubMqtt(@RequestParam("topic") String topic) {
        mqttUtil.unsubscribe(topic);
        return "success";  //To change body of created methods use File | Settings | File Templates.
    }

    @GetMapping("lottery")
    public String lotteryOcr(){
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
        try{
            String filePath = "src/main/resources/lottery/123.jpg";
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            System.out.println(imgParam);
            String param = "image=" + imgParam;
            System.out.println(param);

            String accessToken = getToken();
            String result = HttpUtil.post(url, accessToken, param);
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public String getToken(){
        String token=null;
//        String key = "baiduaip:token";
//        try {
//            if (redisUtil.hasKey(key)) {
//                token = redisUtil.get(key).toString();
//            } else {
                String tokenUrl = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+ aipOcrConfig.getApiKey() +"&client_secret="+aipOcrConfig.getSecretKey();
                String body = HttpRequest.post(tokenUrl).execute().body();
                JSONObject jsonObject = JSONUtil.parseObj(body);
                token = jsonObject.get("refresh_token").toString();
//                redisUtil.set(key,token,2590000);
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
        return token;
    }
}
